package com.cowin.base.auth.jwt;

import com.alibaba.fastjson.JSONObject;
import com.cowin.base.result.Result;
import com.cowin.base.result.ResultGenerator;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.Serializable;

/**
 * Copyright (C), 1998-2018, 奇瑞信息
 *
 * @author : 于超
 * @Date: 2019/9/18 10:40
 * @Description:
 */
@Component
public class JwtAuthenticationEntryPoint implements AuthenticationEntryPoint, Serializable {

    private static final long serialVersionUID = -8970718410437077606L;

    @Override
    public void commence(HttpServletRequest request,
                         HttpServletResponse response,
                         AuthenticationException authException) throws IOException {
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json; charset=utf-8");
        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Cache-Control", "no-cache");
        Result result;
        if (authException instanceof BadCredentialsException) {
            result = ResultGenerator.genFailResult("身份认证失败，密码或用户名输入错误");
        } else {
            result = ResultGenerator.genUnauthorized();
        }
        response.getWriter().write(JSONObject.toJSONString(result));
    }
}
